package java_thinking.unit_21._21_2;

/**
 * @Desc:   测试synchronized(object)\synchronized(this) 区别，
 * @author: cww
 * @DateTime: 2019/5/30 10:01
 */

public class TestBlockObject {
    public static void main(String[] args) {
        TestBlockObject test = new TestBlockObject();
        MyTest m1 = test.new MyTest(test);
        m1.setName("1");
        m1.run();
        MyTest m2 = test.new MyTest(test);
        m2.setName("2");
        m1.start();
        m2.start();
    }
    class MyTest extends Thread {
        /**
         * 局部变量
         */
        private Object o;
        private MyTest(Object o) {
            this.o = o;
        }

        @Override
        public void run() {
            //这里对this，即当前类进行加锁，从打印出的控制台可以看出，两个线程内的 Object 互不影响，
            // 即使一个线程修改了 o 的指向地址
            synchronized (this) {

                System.out.println(MyTest.currentThread().getName() + " " + o.hashCode());
                if ("2".equals(MyTest.currentThread().getName())) {
                    o = new Object();
                    System.out.println("got Thread 2");
                }
                for (int i = 0; i < 10; i++) {
                    System.out.println("线程:"+MyTest.currentThread().getName()+" change a ==" +
                            + i + " o hashCode:" + o.hashCode());
                }
            }
        }
    }
}
